package com.liuyfly.leetcode.questions;

import lombok.extern.slf4j.Slf4j;

/**
 * @author liuyangfang at 2022-08-21 03:30
 */
@Slf4j
public class Question0004 {

    /**
     * 给定两个大小分别为 m 和 n 的正序（从小到大）数组 nums1 和 nums2。请你找出并返回这两个正序数组的 中位数 。 算法的时间复杂度应该为
     * O(log (m+n)) 。 <br/>
     * <br/>
     * 链接：https://leetcode.cn/problems/median-of-two-sorted-arrays
     */
    public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int[] number = new int[nums1.length + nums2.length];
        int firstCurrent = 0, secondCurrent = 0;
        for (int i = 0; i < number.length; i++) {
            if (firstCurrent >= nums1.length) {
                number[i] = nums2[secondCurrent];
                secondCurrent++;
            } else if (secondCurrent >= nums2.length) {
                number[i] = nums1[firstCurrent];
                firstCurrent++;
            } else if (nums1[firstCurrent] < nums2[secondCurrent]) {
                number[i] = nums1[firstCurrent];
                firstCurrent++;
            } else if (nums1[firstCurrent] >= nums2[secondCurrent]) {
                number[i] = nums2[secondCurrent];
                secondCurrent++;
            }
        }

        if (number.length % 2 == 0) {
            return ((double) number[number.length / 2 - 1] + (double) number[number.length / 2]) / 2;
        } else {
            return number[number.length / 2];
        }
    }

    public static void main(String[] args) {
        int[] nums1 = { 2, 2, 4, 4 };
        int[] nums2 = { 2, 2, 4, 4 };
        double result = findMedianSortedArrays(nums1, nums2);
        log.info("result:{}", result);
    }
}
